package com.ayf.payment.game.api.wx;

import com.ayf.payment.game.api.httpclient.MyRequestConfig;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.utils.AESUtil;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.JsonUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Description: HttpClient封装类
 * @Author: zh-liang
 */
public class WxHttpUtil {


    public static JSONObject doGet(String traceId,String url) {
        //创建get请求
        HttpGet httpGet = new HttpGet(url);
        return getJsonObject(traceId,httpGet);
    }

    public static JSONObject doPost(String traceId,String url, String data) {
        //创建post请求
        HttpPost httpPost = new HttpPost(url);
        //设置参数
        httpPost.setEntity(new StringEntity(data, "utf-8"));
        return getJsonObject(traceId,httpPost);
    }

    public static CommonResult testWsdlConnection(String address) throws Exception {
        int status = 404;
        try {
            URL urlObj = new URL(address);
            HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
            oc.setRequestMethod("POST");
            oc.setUseCaches(false);
            oc.setConnectTimeout(3000); // 设置超时时间
            status = oc.getResponseCode();// 请求状态
            if (200 == status) {
                // 200是请求地址顺利连通。。
                return new CommonResult(CommonConstants.RETURN_SUCCESS,"正常");
            }
        } catch (Exception e) {
            return  new CommonResult(-1,"验证异常");
        }
        return  new CommonResult(-1,"验证异常");
    }

    private static JSONObject getJsonObject(String traceId,HttpRequestBase httpRequestBase) {
        //创建客户端
        HttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonObject = null;
        try {
            //执行请求，获取响应数据
            HttpResponse httpResponse = httpClient.execute(httpRequestBase);
            //判断页面请求是否成功
            int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpStatusCode == 200) {
                //将响应数据转换为字符串
                String str = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
                LogPortal.info("{} 请求成功，返回报文:{}",traceId,str);
                //将字符串转换为JSONObject类型
                try {
                    jsonObject = new JSONObject(str);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                String str = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
                LogPortal.info("{} 请求失败，httpStatusCode:{}，返回报文:{}",traceId,httpStatusCode,str);
            }
        } catch (IOException e) {
            LogPortal.error("{} 请求失败，发生{}异常",traceId,e.getClass().getName());
        }
        return jsonObject;
    }
    public static void xmlPost(String urlStr ,String xmlInfo) {
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            con.setRequestProperty("Pragma", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");

            OutputStreamWriter out = new OutputStreamWriter(con
                    .getOutputStream());

            System.out.println("urlStr=" + urlStr);
            System.out.println("xmlInfo=" + xmlInfo);
            out.write(new String(xmlInfo.getBytes("ISO-8859-1")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con
                    .getInputStream()));
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
                System.out.println(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static CommonResult<T> doPostGetWay(String url,String info,String traceId) throws Exception {
        LogPortal.info("{} WXGateway 请求微信网关开始 url[{}] 加密信息[{}]",traceId,  url,info);
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectTimeout(6 * 1000).
                setConnectionRequestTimeout(10 * 1000).
                setSocketTimeout(10*1000). //超时最大等待时间 单位:秒
                build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        HttpPost post = new HttpPost(url);
        info= AESUtil.aes128Encrypt(info,WxGatewayConfig.SECRET_KEY);
        post.setHeader("EncryptedInformation", info);
        post.setConfig(MyRequestConfig.getRequestConfig());
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        CloseableHttpResponse response = null;
        long startTime = System.currentTimeMillis();
        try {
            response = client.execute(post);
            if (response != null) {
                int responseCode = response.getStatusLine().getStatusCode();
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String str = EntityUtils.toString(response.getEntity(), "utf-8");
                    long endTime = System.currentTimeMillis();
                    LogPortal.info("{}WXGateway 请求支付网关结束，耗时:{}ms，responseCode={} 返回报文:{}",traceId,  (endTime - startTime),responseCode,str);
                    return JsonUtils.fromJson(str, CommonResult.class);
                }
            }
        } catch (Exception e) {
            LogPortal.error("{} WXGateway 请求微信网关异常[{}]",e,traceId,url);
            return new CommonResult(-1,"验证异常");
        }
        return new CommonResult(-1,"");
    }

    public static String postJsonData(String urlStr, String json) {

        try {
            URL url = new URL(urlStr);
            HttpURLConnection http =   (HttpURLConnection) url.openConnection();

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type","text/xml");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒

            http.connect();
            OutputStream os= http.getOutputStream();
            os.write(json.getBytes("UTF-8"));//传入参数
            os.flush();
            os.close();

            InputStream is =http.getInputStream();
            int size =is.available();
            byte[] jsonBytes =new byte[size];
            is.read(jsonBytes);
            String message=new String(jsonBytes,"UTF-8");
            return "返回信息"+message;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "createMenu 失败";
    }
 }
